package com.hiwan.system.web.file;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hiwan.platform.util.StackTraceUtil;
import com.hiwan.system.common.base.BaseController;
import com.hiwan.system.pojo.FileInfo;
import com.hiwan.system.pojo.HiwanFile;
import com.hiwan.system.service.file.FileInfoService;
import com.hiwan.system.service.file.FileService;
import com.hiwan.system.util.UserCacheUtils;

/**
 * 
 * Datetime   ： 2015年10月29日 上午10:48:20<br>
 * Title      :  FileController.java<br>
 * Description:   <br>
 * Company    :  hiwan<br>
 * @author cbj
 *
 */
@Controller
@RequestMapping("/file")
public class FileController extends BaseController{

	@Autowired
	private FileService fileService;
	@Autowired
	private FileInfoService fileInfoService;

	/**
	 * 下载上传到服务器的文件
	 * 
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/downloadFile.do")
	public ResponseEntity<byte[]> downloadFile(String attachFileName, String fileServerName,
			String belongOrg, String fileType, HttpServletRequest request) throws IOException {
		HiwanFile file = fileService.getFile(fileServerName, belongOrg, fileType);
		HttpHeaders headers = new HttpHeaders();  
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	    headers.setContentDispositionFormData("attachment", URLEncoder.encode(attachFileName, "UTF-8"));
	    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file.getFile()),headers,HttpStatus.OK); 
	}

	/**
	 * 删除文件
	 * 
	 * @return
	 */
	@RequestMapping("/deleteFile.do")
	public @ResponseBody String[] deleteFile(FileInfo fileInfo,
			String fileType) {
		
		String[] data = null;
		try {
			fileService.deleteFile(fileInfo, fileType);
		} catch (Exception e) {
			logger.error(StackTraceUtil.getStackTrace(e));
			data = new String[] { "error", "删除失败！" };
			return data;
		}
		data = new String[] { "ok", "删除成功！" };
		return data;
	}

	/**
	 * 上传文件
	 * 
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/upload.do")
	public @ResponseBody String upload(@RequestParam("file") MultipartFile file,String busiId, String orgId,HttpServletResponse response) {
			String retjson = null;
			String filePath = null;
			FileInfo fileInfo = null;
			try{
				if ((filePath = fileService.createFile(busiId, orgId, file)) != null) {
					fileInfo = new FileInfo();
					
					String userId = UserCacheUtils.getUser().getUserId();
					fileInfo.setUserId(userId);
					//由于IE8下上传控件有问题,所以固定当前ID为UUID
					if (busiId == null || "".equals(busiId)){
						fileInfo.setAttachId(com.hiwan.platform.utils.StringUtils.getUUID());
					}else{
						fileInfo.setAttachId(busiId);
					}
					fileInfo.setBelongOrg(StringUtils.isBlank(orgId)?UserCacheUtils.getOrgId():orgId);
					fileInfo.setFileName(filePath.substring(filePath.lastIndexOf('/') + 1));
					fileInfo.setOriginName(file.getOriginalFilename());
					fileInfo.setFilePath(busiId);
					fileInfoService.insertFilesInfo(fileInfo);
					retjson = "{\"md5Name\":\""+fileInfo.getFileName()+"\",\"filePath\":\""+filePath+"\",\"fileId\":\""+fileInfo.getFileId()+"\",\"attachId\":\""+busiId+"\"}";	
				}
		} catch (Exception e) {
			logger.error(StackTraceUtil.getStackTrace(e));
			response.setStatus(500);
			return "{ \"error\": \"文件上传失败！\",\"md5Name\":"+fileInfo.getFileName()+"}";
		}
		return retjson;
	}

	@RequestMapping("/checkExsits.do")
	public @ResponseBody String checkExsits() {
		return "0";
	}
}
